package com.liull.netty.nio.helloworld;

import cn.hutool.core.lang.Console;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @Author: liull
 * @Description: 黑马入门netty 案例
 * @Date: Created in 12:25 2021/7/24
 * @Modified By:
 */
public class HelloServer {
    public static void main(String[] args) throws InterruptedException {
        final ChannelFuture future = new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 将 ByteBuf解码为字符串
                        ch.pipeline().addLast(new StringDecoder());
                        // 入站处理器
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                Console.log(msg);
                                // super.channelRead(ctx, msg);
                            }
                        });
                    }
                }).bind(8989)
                .sync();
        future.channel().closeFuture().sync();

    }
}
